package com.efounder.chat.utils;

import android.util.Log;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.AppContext;
import com.pansoft.library.CloudDiskBasicOperation;

import org.json.JSONObject;

import static com.efounder.form.util.CloudUtil.CLOUD_BASE_URL;
import static com.efounder.form.util.CloudUtil.CREATEUSER;
import static com.efounder.form.util.CloudUtil.DOWNURL;
import static com.efounder.form.util.CloudUtil.PARENTID;

/**
 * 七牛上传工具类
 * 上传视频、图片、语音 返回在线url 并封装struct
 * Created by long on 2016/7/27.
 */

public class MessagePanSoftUtils {

    private static final String TAG = "MessagePanSoftUtils";

    private static CloudDiskBasicOperation operation = new CloudDiskBasicOperation();

    //property为宽高比,时长等信息 (也可以是一个json字符串)
    public static void sendMsg(final String msgPath, final String property,
                               final ChatSenderFragment.PreSendMessageCallback preSendMessageCallback,
                               final int messagechildType, byte toUserType) {
        final IMStruct002 imStruct002 = getStruct("%s%", msgPath, property, messagechildType, toUserType);
        if (preSendMessageCallback != null) {
            preSendMessageCallback.preSendMessage(imStruct002);
        }
        //preSend之后,上传,sendPre
        upload(msgPath, imStruct002, preSendMessageCallback, messagechildType);

    }

    public static void upload(final String msgPath, final IMStruct002 imStruct002,
                              final ChatSenderFragment.PreSendMessageCallback preSendMessageCallback, final int messageChildType) {
        // if (messageChildType == MessageChildTypeConstant.subtype_image) {//图片类型，使用图片上传Manager，32K阈值32K分片上传
        final String fileName = msgPath.substring(msgPath.lastIndexOf("/") + 1, msgPath.length()).replace(".pic", "");

        try {
            operation.cloudDiskUploadWeChatFile(msgPath, fileName, CREATEUSER, PARENTID, CLOUD_BASE_URL, new CloudDiskBasicOperation.UploadProgress() {
                @Override
                public void onUploadProgress(long bytesRead, long contentLength, boolean done) {
                    float pro = (float) ((float) bytesRead / (float) contentLength);

                    // Log.i("pro", pro + "");
                    int progress = (int) (pro * 100);
    //                Log.i("progress", progress + "");
                    if (preSendMessageCallback != null) {
                        imStruct002.putExtra("progress", progress);
                        preSendMessageCallback.updateProgress(imStruct002, progress);
                    }
                }
            }, new CloudDiskBasicOperation.ReturnBack() {
                @Override
                public void onReturnBack(String result) {
                    String fileid = "";
                    String resultString = null;
                    try {
                        JSONObject resultObject = new JSONObject(result);
                        resultString = resultObject.getString("result");
                        if (resultObject.has("fileid")) {
                            fileid = resultObject.getString("fileid");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if ("success".equals(resultString)) {
                        /**图片、视频、语音等资源路径*/
                        String resUrl = String.format(CLOUD_BASE_URL + DOWNURL, fileid);
                        Log.i(TAG, resUrl);
                        if (preSendMessageCallback != null) {
                            //如果是文件，传fileid，保持与电脑端和iOS一致 2017.7.3
                            if (messageChildType == MessageChildTypeConstant.subtype_file) {
                                resUrl  =fileid;
                            }

                            String message = imStruct002.getMessage();
                            message = message.replaceAll("%s%", resUrl);
                            imStruct002.setMessage(message);
                            preSendMessageCallback.sendPreMessage(imStruct002);
                        }
                    } else {
                        Log.e("上传失败", result + "");
                        Toast.makeText(AppContext.getInstance(), R.string.common_text_upload_fail_please_check_your_network,
                                Toast.LENGTH_SHORT).show();
                        if (preSendMessageCallback != null) {
                            imStruct002.putExtra("progress", -1);
                            preSendMessageCallback.updateProgress(imStruct002, -1);
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(AppContext.getInstance(), R.string.common_text_upload_fail,
                    Toast.LENGTH_SHORT).show();
            if (preSendMessageCallback != null) {
                imStruct002.putExtra("progress", -1);
                preSendMessageCallback.updateProgress(imStruct002, -1);
            }
        }
        // }
    }


    /**
     * 获取创建消息体
     * @param resUrl 文件资源网络路径（%s 替换）
     * @param path 本地路径
     * @param property 消息体 json 字符串
     * @param messageChildType 消息类型
     * @param toUserType
     * @return
     */
    private static IMStruct002 getStruct(String resUrl, String path, String property, int messageChildType, byte toUserType) {
        IMStruct002 imStruct002 = null;
        switch (messageChildType) {
            case MessageChildTypeConstant.subtype_image:
                imStruct002 = StructFactory.getInstance().createImageStruct(resUrl, path, property, toUserType);
                break;
            case MessageChildTypeConstant.subtype_voice:
                imStruct002 = StructFactory.getInstance().createVoiceStruct(resUrl, path, property, toUserType);
                break;
            case MessageChildTypeConstant.subtype_smallVideo:
                imStruct002 = StructFactory.getInstance().createVideoStruct(resUrl, path, property, toUserType);
                break;
//            case MessageChildTypeConstant.subtype_location:
//                imStruct002 = StructFactory.getInstance().createMapStruct(resUrl, toUserType);
//                break;
            case MessageChildTypeConstant.subtype_file:
                String url = String.format(CLOUD_BASE_URL + DOWNURL, resUrl);
                imStruct002 = StructFactory.getInstance().createFileStruct(url, resUrl, path, property, toUserType);
                break;
            case MessageChildTypeConstant.subtype_location:
                imStruct002 = StructFactory.getInstance().createLocationStruct(resUrl, path, property, toUserType);
                break;
            case MessageChildTypeConstant.subtype_secret_image:
                imStruct002 = StructFactory.getInstance().createSecretImgImstrct002(resUrl, path, property, toUserType);
                break;
            case MessageChildTypeConstant.subtype_secret_file:
                imStruct002 = StructFactory.getInstance().createSecretFileImstrct002(resUrl, path, property, toUserType);
                break;
            case MessageChildTypeConstant.subtype_speechRecognize:
                //语音识别
                imStruct002 = StructFactory.getInstance().createSpeechRecgonitionImstrct002(resUrl, path, property, toUserType);
                break;
            default:
                break;
        }

        return imStruct002;
    }


}
